import {
  Component,
  ViewEncapsulation,
  ChangeDetectionStrategy,
  AfterContentInit,
  ElementRef,
  ChangeDetectorRef,
  ContentChild,
} from '@angular/core';
import { InputDirective } from './input.directive';

@Component({
  selector: 'lv-input-lint',
  exportAs: 'lvInputLint',
  templateUrl: './input-lint.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.lv-input-lint]': 'true',
    '[class.lv-input-limit]': '_inputLimit',
  },
})
export class InputLintComponent implements AfterContentInit {
  @ContentChild(InputDirective, { static: false }) textarea: InputDirective;
  _textarea;
  _nativeElement;
  _minRate = 0.1;
  _maxLength: number;
  _currentLength: number;

  _limitInput: boolean = false;

  constructor(
    private _elementRef: ElementRef,
    private _cdr: ChangeDetectorRef,
  ) {
    this._nativeElement = this._elementRef.nativeElement;
  }

  get _inputLimit(): boolean {
    const currentLength = this.getTextAreaLength();
    return currentLength > this._maxLength && currentLength > 0;
  }

  getTextAreaLength(): any {
    const _textarea = this._nativeElement.querySelector('textarea');
    if (!_textarea) {
      return -1;
    }
    return _textarea.value.length;
  }

  ngAfterContentInit(): void {
    const _textarea = this._nativeElement.querySelector('textarea');
    if (!_textarea) {
      return;
    }
    if (typeof this.textarea.lvMaxLength === 'object') {
      this._maxLength = Math.max(this.textarea.lvMaxLength.length, 0);
      this._limitInput = this.textarea.lvMaxLength.limitInput;
    } else {
      this._maxLength = Math.max(this.textarea.lvMaxLength || _textarea.maxLength, 0);
    }

    // 超过最大数量后限制输入
    if (this._limitInput) {
      _textarea.setAttribute('maxLength', this._maxLength);
    }
    this._currentLength = this.getTextAreaLength();

    this.textarea.valueChange$.subscribe((value): void => {
      this._currentLength = value ? value.length : 0;
      this._cdr.markForCheck();
    });
  }
}
